/*
@Time : 2020-06-28 16:46:40
@Author : gen
@File : GroupMember
@Software: GoLand
*/

package models

import (
	"fmt"
	"strings"

	"encoding/json"
	"git.9885.net/lib/go/common/db"
)

type GroupMember struct {

	GroupId int64 `json:"group_id" db:"group_id"` //

	Uid int64 `json:"uid" db:"uid"` //

	Timestamp int `json:"timestamp" db:"timestamp"` // 入群时间,单位：秒

	Nickname string `json:"nickname" db:"nickname"` // 群内昵称

	Mute int8 `json:"mute" db:"mute"` // 群内禁言

}

func (GroupMember) TableName() string {
	return "group_member"
}

// 创建GroupMember
func AddGroupMember(e *GroupMember) (GroupMember, error) {
	_, err := db.Session().InsertInto(e.TableName()).Record(&e).Exec()
	if err != nil {
		return *e, err
	}
	return *e, nil
}


// 获取GroupMember带分页
func GetAllGroupMember(fields []string, sortby []string, order []string, offset int64, limit int64) (ml []interface{}, err error) {
	_, err = db.Session().
		Select(fmt.Sprintf("\"%s\"", strings.Join(fields, "\",\""))).
		From("group_member").
		Limit(uint64(limit)).
		Offset(uint64(offset)).
		Load(&ml)

	return
}


// 获取GroupMember
func GetGroupMemberById(id int) (GroupMember, error) {
	var doc GroupMember
	err := db.Session().Select("*").From("group_member").Where("uid = ? ", id).LoadOne(&doc)
	if err != nil {
		return doc, err
	}
	return doc, nil
}


// 更新GroupMember
func UpdateGroupMemberById(m *GroupMember) error {
	setMap_bytes, _ := json.Marshal(m)
	var setMap map[string]interface{}
	err := json.Unmarshal(setMap_bytes, &setMap)
	if err != nil {
		return err
	}
	rs, err := db.Session().Update("group_member").
		SetMap(setMap).
		Where("uid = m.uid").Exec()
	if err != nil {
		return err
	}else{
		fmt.Println(rs.RowsAffected())
		return nil
	}
}

// 删除GroupMember
func DeleteGroupMember(id int) (err error) {
	rs, err := db.Session().DeleteFrom("group_member").Where("uid = ?", id).Exec()
	if err != nil {
		return
	} else {
		fmt.Println(rs.RowsAffected())
	}
	return
}

//批量删除
func BatchDeleteGroupMember(ids []int) error {
	rs, err := db.Session().DeleteFrom("group_member").Where("uid in ?", ids).Exec()
	if err != nil {
		return err
	} else {
		fmt.Println(rs.RowsAffected())
	}
	return err
}